<?php
namespace app\index\controller;
use \app\index\model\Visit;
use \think\Db;
use \think\Request;
use \think\Response;

/*
{
"ret": "ok",    // ret 值为 ok 时 返回 data 数据 为err时返回msg数据
"ip": "117.25.13.123",  // ip
"data": [
"中国",     // 国家
"福建",     // 省会或直辖市
"福州",     // 地区或城市
"电信",     // 运营商
"361000",  // 邮政编码(暂不提供)
"0592"     // 地区区号(暂不提供)
]
}
 */
class Third {
	public function index(Request $request, Response $response, Visit $visit) {
		$db = Db::name('visit');
		$ip = $request->ip();
		$header = array(
			"token:638bf903950365d2620159756506c265",
		);
		function getLocation($arr) {
			$res = '';
			foreach ($arr as $key => $value) {
				$res .= $value . ' ';
			}
			return $res;
		};
		// 获取ip地址信息
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_URL, 'http://api.ip138.com/query/?ip=' . $ip . '&datatype=jsonp');
		$output = curl_exec($ch);
		$output = json_decode($output);
		curl_close($ch);
		$res = getLocation($output->data);
		// 拼装访问信息录入数据库
		$info = [
			'visit_ip' => $ip,
			'visit_location' => substr($res, 0, strlen($res) - 3),
		];
		return $visit->setVisit($info);
	}
	public function getAllVisitInfo(Visit $visit) {
		$res = $visit->limit(30)->order('id', 'desc')->select();
		$count = $visit->count();
		return ['code' => 200, 'message' => $res, 'count'=> $count];
	}
}
